#! /usr/bin/env python3

from typing import Union, Dict, List
import time

import allure
import logging
import pandas as pd
from yaml import safe_load

from keywords import UiKeyWords, ApiKeyWords


def read_yaml(file_name: str = 'data.yaml') -> dict:
    """读取yaml配置文件，返回字典"""
    with open(f'data/{file_name}', 'r', encoding='utf-8') as f:
        return safe_load(f)


def run_case(keyword: Union[UiKeyWords, ApiKeyWords],
             logger: logging.Logger,
             case: Dict):
    """运行测试用例
        keyword: 关键字驱动实例
        logger : 日志管理器
        case   : 测试用例的相关数据
    """
    case_name = case['name']
    start = time.time()
    logger.info(f'*****开始执行测试用例：{case_name}*****')
    allure.dynamic.story(case_name)
    allure.dynamic.severity(allure.severity_level.CRITICAL)
    with allure.step(f'执行用例{case_name}'):
        for step in case['steps']:
            key = step.get('key')
            kwargs = step.get('args', {})
            logger.info(f'执行操作: {key}, 实际参数: {kwargs}')
            with allure.step(f'执行操作: {key}, 实际参数: {kwargs}'):
                if hasattr(keyword, key):
                    try:
                        getattr(keyword, key)(**kwargs)
                    except Exception as e:
                        logger.error(f"测试用例: {case_name}  {key}操作失败!")
                        allure.attach(body=keyword.screenshot(), name='错误截图',
                                      attachment_type=allure.attachment_type.PNG)
                        raise
                else:
                    msg = f'keyword无{key}属性'
                    logger.error(msg)
                    allure.attach(msg, name='ErrorMsg',
                                  attachment_type=allure.attachment_type.TEXT)
                    raise AttributeError(f'UiKeyWords无{key}属性')
    run = round(time.time() - start, 2)
    logger.info(f'*****测试用例执行完成：{case_name} 用时{run:.2f}秒*****')
